package com.liuchuanzheng.lcz_study_demo.hook;

import android.app.Instrumentation;
import android.content.Context;
import android.os.Build;
import android.os.Handler;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class HookHelper {

    public static final String TARGET_INTENT = "target_intent";
    //测试无效
    public static void hookAMS() throws Exception{

        Object defaultSingleton = null;

        if(Build.VERSION.SDK_INT >= 26){//1
            Class<?> activityManageClazz = Class.forName("android.app.ActivityManager");
            defaultSingleton = FieldUtil.getField(activityManageClazz,null,"IActivityManagerSingleton");
        }else{
            Class<?> activityManageClazz = Class.forName("android.app.ActivityManagerNative");
            defaultSingleton = FieldUtil.getField(activityManageClazz,null,"gDefault");
        }

        Class<?> singletonClazz = Class.forName("android.util.Singleton");

        Field mInstanceField = FieldUtil.getField(singletonClazz,"mInstance");//2

        Object iActivityManager = mInstanceField.get(defaultSingleton);//3

        Class<?> iAcitivityManagerClazz = Class.forName("android.app.IActivityManager");

        Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader()
                ,new Class<?>[]{iAcitivityManagerClazz}
                ,new IActivityManagerProxy(iActivityManager));

        mInstanceField.set(defaultSingleton,proxy);

    }
    public static void hookHandler() throws Exception {

        Class<?> activityThreadClass = Class.forName( "android.app.ActivityThread");

        Object currentActivityThread= FieldUtil.getField (activityThreadClass ,null ,"sCurrentActivityThread" ) ; //1

        Field mHField = FieldUtil.getField (activityThreadClass,"mH" ) ; //12

        Handler mH = (Handler) mHField.get(currentActivityThread);//3

        FieldUtil.setField(Handler.class , mH,"mCallback",new HCallback(mH));


    }
    //测试可用
    public static void hookInstrumentation(Context context) throws Exception{

        Class<?> contextImplClass = Class.forName("android.app.ContextImpl");

        Field mMainThreadField = FieldUtil.getField(contextImplClass,"mMainThread");

        Object activityThread = mMainThreadField.get(context);

        Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");

        Field mInstrumentation = FieldUtil.getField(activityThreadClass,"mInstrumentation");

        FieldUtil.setField(activityThreadClass
                ,activityThread
                ,"mInstrumentation"
                ,new InstrumentationProxy((Instrumentation)mInstrumentation.get(activityThread),context.getPackageManager()));


    }


}

